package com.ztesoft.book.common.utils.context;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.ztesoft.book.common.constant.Constant;
import com.ztesoft.book.common.utils.exception.ServiceException;
import com.ztesoft.book.common.utils.jwt.JwtUtil;
import com.ztesoft.book.common.utils.redis.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Description 获取登录信息工具类
 * @Author YangFan
 * @Date 2021-06-22 15:39
 */
@Component
public final class ShiroContextUtil {

    private ShiroContextUtil() {
    }

    public static String getShiroCacheUser() {
        if (SecurityUtils.getSubject().getPrincipal() != null) {
            String token = SecurityUtils.getSubject().getPrincipal().toString();
            String username = JwtUtil.getClaim(token, Constant.USERNAME);
            Map<String, Object> redisToken = RedisUtils.get(Constant.PREFIX_SHIRO_REFRESH_TOKEN + username, Maps.newHashMap().getClass());
            if (redisToken != null) {
                if (redisToken.containsKey(Constant.REDIS_TOKEN_USER_NAME)) {
                    return JSON.toJSONString(redisToken.get(Constant.REDIS_TOKEN_USER_NAME));
                }
            }
        }
        return "";
    }

    public static <T> T getShiroCacheUser(Class<T> clazz) {
        String json = getShiroCacheUser();
        if (StringUtils.hasLength(json)) {
            return JSON.parseObject(json, clazz);
        }
        throw new ServiceException("token已过期");
    }
}
